import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Tabs,
  Form,
  Modal,
  Table,
  Radio,
  Button,
  Select,
  message,
  Popconfirm,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import GeneralFilterComponent from 'components/GeneralFilterComponent';
import GeneralFormComponent from 'components/GeneralFormComponent';

const TabPane = Tabs.TabPane;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Option } = Select;
const confirm = Modal.confirm;

@connect(({ flickerScreen, loading }) => ({
  flickerScreen,
  loading: loading.models.flickerScreen,
}))
@Form.create()
export default class FlickerScreen extends PureComponent {
state = {
    paramList:{
      pageNo: 1,
      pageSize: 10,
      source: '',
      current: '',
      endTime: '',
      // sortField: 'sequence',
      // sortOrder: 'asc',
      startTime: '',
      status: '',
      title: '',
      version: '',
    },
    imgDialogVisible: false,
    newDialogVisible: false,
    editDialogVisible: false,
    edited: {},
    imgSource: '',
  };

  componentWillMount() {
    const { paramList } = this.state;
    switch(this.props.location.pathname.split('/')[1]) {
      case 'operatingCenter':
        paramList.source = 'up';
      break;
      case 'operatingCenterForXbeauty':
        paramList.source = 'xbeauty';
      break;
      case 'operatingCenterForXflower':
        paramList.source = 'xflower';
      break;
      case 'operatingCenterForUpoint':
        paramList.source = 'upoint';
      break;
      default:
      break;
    }
  }

  componentDidMount() {
    this.getVersionList();
  }

  getScreenList = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let paramBuf = {
      current: paramList.pageNo,
      endTime: '',
      pageSize: paramList.pageSize,
      // sortField: paramList.sortField,
      // sortOrder: paramList.sortOrder,
      source: paramList.source,
      startTime: '',
      status: paramList.status,
      title: paramList.title,
      version: paramList.version,
    }
    if (paramList.dateRange && paramList.dateRange[0]) {
      [paramBuf.startTime, paramBuf.endTime] = [
        paramList.dateRange[0].format('YYYY-MM-DD HH:mm:ss'),
        paramList.dateRange[1].format('YYYY-MM-DD HH:mm:ss'),
      ];
    }
    let postParam = {}
    for (let [key, val] of Object.entries(paramBuf)) {
      if (val !== '' && typeof(val) != 'undefined') {
        postParam[key] = val;
      }
    }
    console.log('postParam', postParam);
    dispatch({
      type: 'flickerScreen/fetchGetScreenList',
      payload: {
        ...postParam
      }
    });
  };

  getVersionList = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    
    let postParam = {
      source: paramList.source
    }
    
    dispatch({
      type: 'flickerScreen/fetchGetScreenVersion',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          paramList.version = res.data && res.data[0] ? res.data[0] : '';
          this.getScreenList();
        } else {

        }
      }
    });
  };

  postNewScreen = (value) => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {
      url: value.url,
      // sequence: value.sequence,
      version: value.version,
      title: value.title,
      source: paramList.source,
    }
    if (value.imgUrl && typeof(value.imgUrl) == 'string') {
      postParam.imgUrl = value.imgUrl
    } else if (value.imgUrl && value.imgUrl.file && value.imgUrl.file.response) {
      postParam.imgUrl = value.imgUrl.file.response.data;
    }
    console.log('postParam', postParam);
    dispatch({
      type: 'flickerScreen/fetchPostAddScreen',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          message.success(`添加成功`);
          paramList.pageNo = 1;
          this.getScreenList();
        } else {
          message.error(`${res.message}`);
        }
      }
    });
  };

  postEditScreen = (value) => {
    const { dispatch } = this.props;
    const { paramList, edited } = this.state;
    let postParam = {
      id: edited.id,
      url: value.url,
      version: value.version,
      title: value.title,
      source: paramList.source,
    }
    if (value.imgUrl && typeof(value.imgUrl) == 'string') {
      postParam.imgUrl = value.imgUrl
    } else if (value.imgUrl && value.imgUrl.file && value.imgUrl.file.response) {
      postParam.imgUrl = value.imgUrl.file.response.data;
    }
    // if (value.sequence !== edited.sequence) {
    //   postParam.sequence = value.sequence;
    // }
    console.log('postParam', postParam);
    dispatch({
      type: 'flickerScreen/fetchPostUpdateScreen',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          message.success(`修改成功`);
          this.getScreenList();
        } else {
          message.error(`${res.message}`);
        }
      }
    });
  };

  postOffLineScreen = (id) => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {
      id: id,
      status: 'UNDER_LINE'
    }
    console.log('postParam', postParam);
    dispatch({
      type: 'flickerScreen/fetchPostOnOffScreen',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          message.success(`下线成功`);
          this.getScreenList();
        } else {
          message.error(`${res.message}`);
        }
      }
    });
  };

  postOnLineScreen = (id) => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    const vm = this;
    let postParam = {
      id: id,
      status: 'ON_LINE'
    }
    console.log('postParam', postParam);
    dispatch({
      type: 'flickerScreen/fetchPostOnOffScreen',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          message.success(`上线成功`);
          vm.getScreenList();
        } else {
          message.error(`${res.message}`);
        }
      }
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.pageNo = pagination.current;
    paramList.pageSize = pagination.pageSize;
    this.getScreenList();
  };

  handleFormReset = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.pageNo = 1;
    this.getScreenList();
  };

  handleFormSearch = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.pageNo = 1;
    this.getScreenList();
  };

  handleAddFormSubmit = (value, err) => {
    if (!err) {
      this.postNewScreen(value);
      this.setState({
        newDialogVisible: false
      });
    }
  };

  handleAddFormCancel = (value) => {
    this.setState({
      newDialogVisible: false
    });
  };

  handleEditFormSubmit = (value, err) => {
    if (!err) {
      this.postEditScreen(value);
      this.setState({
        editDialogVisible: false
      });
    }
  };

  handleEditFormCancel = (value) => {
    this.setState({
      editDialogVisible: false
    });
  };

  handleShowNewDialog = () => {
    this.setState({
      newDialogVisible: true
    });
  };

  showImgDialog = (row) => {
    this.setState({
      imgDialogVisible: true,
      imgSource: row.imgUrl,
    });
  };

  handleImgClose = (row) => {
    this.setState({
      imgDialogVisible: false,
      imgSource: '',
    });
  };

  editScreen = (row) => {
    const { edited } = this.state;
    Object.assign(edited, row);
    this.setState({
      editDialogVisible: true
    });
  };

  offlineScreen = (row) => {
    this.postOffLineScreen(row.id);
  };

  onlineScreen = (row) => {
    this.postOnLineScreen(row.id);
  };

  handleVersionChange = (val) => {
    const { paramList } = this.state;
    paramList.version = val;
    this.getScreenList();
  };

  render() {
    const { flickerScreen: { flickerScreenData, versionList }, loading } = this.props;
    const { newDialogVisible, paramList, imgSource, imgDialogVisible, editDialogVisible, edited } = this.state;

    let versionOptions = [];
    versionList.forEach((val, index, arr) => {
      let _buf = {
        label: val,
        value: val,
      }
      versionOptions.push(_buf);
    });

    
    
    const tableColumns = [{
      title: '序号',
      dataIndex: 'demo',
      key: 'demo',
      render: (text, record, index) => {
        return <span>{index + 1 + ( flickerScreenData.pagination.current - 1 ) * flickerScreenData.pagination.size}</span>
      }
    }, {
      title: 'screen标题',
      dataIndex: 'title',
      key: 'title',
      render: val => `${val}`
    }, {
      title: 'URL',
      dataIndex: 'url',
      key: 'url',
      render: val => `${val}`
    }, {
      title: '图片',
      dataIndex: 'imgUrl',
      key: 'imgUrl',
      render: (text, record, index) => {
        return (
          <a href="javascript:;" onClick={() => this.showImgDialog(record)}>
            点击查看
          </a>
        );
      },
    // }, {
    //   title: '排序',
    //   dataIndex: 'sequence',
    //   key: 'sequence',
    //   render: val => `${val}`
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: val => `${val}`
    }, {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
      render: val => `${val}`
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text, record, index) => {
        return (
          <span>{text === 'ON_LINE' ? '已上线' : ( text === 'WAIT_LINE' ? '等待上线' : ( text === 'UNDER_LINE' ? '下线' : text ) )}</span>
        );
      },
    }, {
      title: '操作',
      dataIndex: 'demo3',
      key: 'demo3',
      render: (text, record, index) => {
        return (
          <div>
            <a href="javascript:;" style={{display: 'inlineBlock', marginRight: 10}} onClick={() => this.editScreen(record)}>
              编辑
            </a>
            {
              record.status === 'ON_LINE' ? 
              <Popconfirm title="确认下线" onConfirm={() => this.offlineScreen(record)}>
                <a href="javascript:;">
                  下线
                </a>
              </Popconfirm> :
              (
                record.status === 'WAIT_LINE' ? 
                <span>
                  <Popconfirm title="确认上线" onConfirm={() => this.onlineScreen(record)}>
                    <a href="javascript:;" style={{display: 'inlineBlock', marginRight: 10}}>
                      上线
                    </a>
                  </Popconfirm>
                  <Popconfirm title="确认下线" onConfirm={() => this.offlineScreen(record)}>
                    <a href="javascript:;">
                      下线
                    </a>
                  </Popconfirm>
                </span> :
                ''
              )
            }
              
          </div>
        );
      },
    }]

    const searchColumns = [{
      type: 'input',
      value: 'title',
      label: 'screen标题',
      placeholder: '请输入',
    }, {
      type: 'select',
      value: 'status',
      label: '状态',
      placeholder: '请选择',
      selectOption: [{
        value: 'ON_LINE',
        label: '上线',
      }, {
        value: 'WAIT_LINE',
        label: '待上线',
      }, {
        value: 'UNDER_LINE',
        label: '下线',
      }]
    }, {
      type: 'rangePicker',
      value: 'dateRange',
      label: '创建时间',
      placeholder: ['起始时间', '结束时间'],
    }]

    const addFormColumns = [{
      // type: 'input',
      // value: 'sequence',
      // label: '序号',
      // rules: {
      //   required: true,
      //   message: '请输入正确的序号',
      // },
    }, {
      type: 'select',
      value: 'version',
      label: '版本号',
      selectOption: versionOptions,
      rules: {
        required: true,
        message: '请输入正确的版本号',
        pattern: /^[0-9]+[.][0-9]+[.][0-9]+$/,
      },
    }, {
      type: 'input',
      value: 'title',
      label: 'screen标题',
      rules: {
        required: true,
        message: '请输入正确的screen标题',
      },
    }, {
      type: 'input',
      value: 'url',
      label: 'URL',
      rules: {
        required: false,
        message: '请输入正确的URL',
      },
    }, {
      type: 'upload',
      value: 'imgUrl',
      label: '选择图片',
      url: '/user/creditMarket/upload/',
      rules: {
        required: true,
        message: '请选择一张图片',
      },
      tips: '支持png、jpg格式，大小不超过1M'
    }];

    const editFormColumns = [{
      // type: 'input',
      // value: 'sequence',
      // label: '序号',
      // initialValue: edited.sequence,
      // rules: {
      //   required: true,
      //   message: '请输入正确的序号',
      // },
    }, {
      type: 'select',
      value: 'version',
      label: '版本号',
      initialValue: edited.version,
      selectOption: versionOptions,
      rules: {
        required: true,
        message: '请输入正确的版本号',
        pattern: /^[0-9]+[.][0-9]+[.][0-9]+$/,
      },
    }, {
      type: 'input',
      value: 'title',
      label: 'screen标题',
      initialValue: edited.title,
      rules: {
        required: true,
        message: '请输入正确的screen标题',
      },
    }, {
      type: 'input',
      value: 'url',
      label: 'URL',
      initialValue: edited.url,
      rules: {
        required: false,
        message: '请输入正确的URL',
      },
    }, {
      type: 'upload',
      value: 'imgUrl',
      label: '选择图片',
      initialValue: edited.imgUrl,
      url: '/user/creditMarket/upload/',
      rules: {
        required: true,
        message: '请选择一张图片',
      },
      tips: '支持png、jpg格式，大小不超过1M'
    }];

    const addDialogSet = {
      visible: newDialogVisible,
      title: '新建screen',
    }

    const editDialogSet = {
      visible: editDialogVisible,
      title: '编辑screen',
    }

    const versionItems = versionList ? versionList.map((item) => {
      return <Option value={item} key={item}>{item}</Option>
    }) : '';

    return (
      <PageHeaderLayout title="screen配置">
        <Card bordered={false}>
          <div style={{marginBottom: 20}}>
            <Button onClick={this.handleShowNewDialog}>新建Screen</Button>
            <Select style={{ float: 'right', width: 120 }} placeholder={versionList.length > 0 ? versionList[0] : ''} onChange={this.handleVersionChange}>
              { versionItems }
            </Select>
          </div>

          <div style={{marginBottom: 20}}>
            <GeneralFilterComponent
            itemList={searchColumns}
            onClear={this.handleFormReset}
            onSearch={this.handleFormSearch}
            />
          </div>

          <GeneralTableComponent
            loading={loading}
            data={flickerScreenData}
            columns={tableColumns}
            onChange={this.handleStandardTableChange}
            showSizeChanger
          />
            
          <GeneralFormComponent 
            itemList={addFormColumns}
            onSubmit={this.handleAddFormSubmit}
            onCancel={this.handleAddFormCancel}
            isDialog={true}
            dialogConfig={addDialogSet}
          />

          <GeneralFormComponent 
            itemList={editFormColumns}
            onSubmit={this.handleEditFormSubmit}
            onCancel={this.handleEditFormCancel}
            isDialog={true}
            dialogConfig={editDialogSet}
          />

          <Modal
            title="查看图片"
            visible={imgDialogVisible}
            onOk={this.handleImgClose}
            onCancel={this.handleImgClose}
          >
            <img src={imgSource} style={{width: '100%'}} />
          </Modal>
        </Card>
      </PageHeaderLayout>
    );
  }
}